package com.itheima.reggie.exception;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandle {

    @ExceptionHandler(Exception.class)
    public R unexpectedException(Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
        return R.error("未知错误");
    }

    @ExceptionHandler(CustomException.class)
    public R duplicateDatabaseUserNameException(CustomException e) {
        System.err.println(e.getClass().getName() + ":" + e.getMessage());
        return R.error(e.getMessage());
    }

    @ExceptionHandler(NullPointerException.class)
    public R nullPointerOperationException(NullPointerException e) {
        System.err.println("空指针异常信息--->" + e.getClass().getName() + ":" + e.getMessage());
        return R.error(e.getMessage());
    }

    /**
     * 异常处理方法
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> doSQLException(SQLIntegrityConstraintViolationException ex){
        log.error(ex.getMessage());
        if(ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return R.error(msg);
        }
        return R.error("未知错误");
    }

}
